<template>
  <el-select style="width: 100%" v-model="select" :filterable="filterable" :placeholder="placeholder||'请选择'" :multiple="multiple" @change="change">
    <el-option v-for="(item, index) in opts" :key="index" :label="item.name" :value="item.id"></el-option>
  </el-select>
</template>

<script>
import request from '@/utils/request';
export default {
    name: 'SelectbyApis',
  props: {
    value: {
      type: [String, Number],
      default: null,
    },
    placeholder: {
      type: String,
      default: "",
    },
    multiple: {
      type: Boolean,
      default: true,
    },
    api: {
        type: [String, Function],
        require: true
    },
    filterable: {
        type: Boolean,
        default: false
    }
  },
  data() {
    return {
      opts: [],
      select: [],
      optionMaps: {},
      params: {page: 1,pageSize: 999}
    };
  },
  watch: {
    value: {
      handler(val) {
        if(val) {
            const list = JSON.parse(val);
            this.select = list.map(item => Number(item.id))
        }else{
            this.select = []
        }
      },
      immediate: true,
    },
  },
  created() {    
    this.init()
  },
  methods: {
    async init() {
        try {
           if(typeof this.api == 'string') {
                const res = await request({url: this.api, method: 'get', params: this.params})
                this.setData(res.data)
            }else{
                const res = await this.api(this.params);
                this.setData(res.data)
            }
        } catch (error) {
            
        }
    },
    setData(data) {
        this.opts = data;
        for (let i = 0; i < data.length; i++) {
            this.optionMaps[data[i].id] = data[i].name;
        }
    },
    change(e) {
        var list = e.map((id) => {
            const obj = {};
            obj.id = id;
            obj.name = this.optionMaps[id];
            return obj;
        });

    //   console.log(list);
        let checkItem = []
        if(e) {
            checkItem = this.opts.filter(item => {
                if(e.includes(item.id)){
                    return item;
                }
            })
        }

        this.$emit("input", list && list.length ? JSON.stringify(list) : null);
        this.$emit('change', checkItem);
    },
  },
};
</script>

<style scoped lang="scss"></style>
